package com.mj.haier.calc.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.mj.haier.calc.domain.AzFinSettleBill;
import com.mj.haier.calc.repository.AzFinSettleBillRepository;
import com.mj.haier.calc.repository.search.AzFinSettleBillSearchRepository;
import com.mj.haier.calc.sharding.generator.ShardingKeyGenerator;
import com.mj.haier.calc.web.rest.errors.BadRequestAlertException;
import com.mj.haier.calc.web.rest.util.HeaderUtil;
import com.mj.haier.calc.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing AzFinSettleBill.
 */
@RestController
@RequestMapping("/api")
public class AzFinSettleBillResource {

    private final Logger log = LoggerFactory.getLogger(AzFinSettleBillResource.class);

    private static final String ENTITY_NAME = "microCalcAzFinSettleBill";

    private final AzFinSettleBillRepository azFinSettleBillRepository;

    private final AzFinSettleBillSearchRepository azFinSettleBillSearchRepository;

    public AzFinSettleBillResource(AzFinSettleBillRepository azFinSettleBillRepository, AzFinSettleBillSearchRepository azFinSettleBillSearchRepository) {
        this.azFinSettleBillRepository = azFinSettleBillRepository;
        this.azFinSettleBillSearchRepository = azFinSettleBillSearchRepository;
    }

    /**
     * POST  /az-fin-settle-bills : Create a new azFinSettleBill.
     *
     * @param azFinSettleBill the azFinSettleBill to create
     * @return the ResponseEntity with status 201 (Created) and with body the new azFinSettleBill, or with status 400 (Bad Request) if the azFinSettleBill has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/az-fin-settle-bills")
    @Timed
    public ResponseEntity<AzFinSettleBill> createAzFinSettleBill(@Valid @RequestBody AzFinSettleBill azFinSettleBill) throws URISyntaxException {
        log.debug("REST request to save AzFinSettleBill : {}", azFinSettleBill);
        if (azFinSettleBill.getId() != null) {
            throw new BadRequestAlertException("A new azFinSettleBill cannot already have an ID", ENTITY_NAME, "idexists");
        }
        Long id = ShardingKeyGenerator.keyGenerator().longValue();
        azFinSettleBill.setId(id);
        StringBuilder settleId = new StringBuilder("AZ");
        switch(azFinSettleBill.getSettleItem()){
            case "1":
            case "0":
                settleId.append(azFinSettleBill.getSettleItem());
                break;
            default:
                settleId.append("D");
        }
        azFinSettleBill.setSettleId(settleId.append(String.valueOf(id)).toString());
        AzFinSettleBill result = azFinSettleBillRepository.save(azFinSettleBill);
        azFinSettleBillSearchRepository.save(result);
        return ResponseEntity.created(new URI("/api/az-fin-settle-bills/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /az-fin-settle-bills : Updates an existing azFinSettleBill.
     *
     * @param azFinSettleBill the azFinSettleBill to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated azFinSettleBill,
     * or with status 400 (Bad Request) if the azFinSettleBill is not valid,
     * or with status 500 (Internal Server Error) if the azFinSettleBill couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/az-fin-settle-bills")
    @Timed
    public ResponseEntity<AzFinSettleBill> updateAzFinSettleBill(@Valid @RequestBody AzFinSettleBill azFinSettleBill) throws URISyntaxException {
        log.debug("REST request to update AzFinSettleBill : {}", azFinSettleBill);
        if (azFinSettleBill.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        AzFinSettleBill result = azFinSettleBillRepository.save(azFinSettleBill);
        azFinSettleBillSearchRepository.save(result);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, azFinSettleBill.getId().toString()))
            .body(result);
    }

    /**
     * GET  /az-fin-settle-bills : get all the azFinSettleBills.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of azFinSettleBills in body
     */
    @GetMapping("/az-fin-settle-bills")
    @Timed
    public ResponseEntity<List<AzFinSettleBill>> getAllAzFinSettleBills(Pageable pageable) {
        log.debug("REST request to get a page of AzFinSettleBills");
        Page<AzFinSettleBill> page = azFinSettleBillRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/az-fin-settle-bills");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /az-fin-settle-bills/:id : get the "id" azFinSettleBill.
     *
     * @param id the id of the azFinSettleBill to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the azFinSettleBill, or with status 404 (Not Found)
     */
    @GetMapping("/az-fin-settle-bills/{id}")
    @Timed
    public ResponseEntity<AzFinSettleBill> getAzFinSettleBill(@PathVariable Long id) {
        log.debug("REST request to get AzFinSettleBill : {}", id);
        Optional<AzFinSettleBill> azFinSettleBill = azFinSettleBillRepository.findById(id);
        return ResponseUtil.wrapOrNotFound(azFinSettleBill);
    }

    /**
     * DELETE  /az-fin-settle-bills/:id : delete the "id" azFinSettleBill.
     *
     * @param id the id of the azFinSettleBill to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/az-fin-settle-bills/{id}")
    @Timed
    public ResponseEntity<Void> deleteAzFinSettleBill(@PathVariable Long id) {
        log.debug("REST request to delete AzFinSettleBill : {}", id);

        azFinSettleBillRepository.deleteById(id);
        azFinSettleBillSearchRepository.deleteById(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/az-fin-settle-bills?query=:query : search for the azFinSettleBill corresponding
     * to the query.
     *
     * @param query the query of the azFinSettleBill search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/az-fin-settle-bills")
    @Timed
    public ResponseEntity<List<AzFinSettleBill>> searchAzFinSettleBills(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of AzFinSettleBills for query {}", query);
        Page<AzFinSettleBill> page = azFinSettleBillSearchRepository.search(queryStringQuery(query), pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/az-fin-settle-bills");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
